using Main;
using Main.Details;
using UnityEditor;
using UnityEngine;
using UnityEngine.Tilemaps;

[ExecuteInEditMode]
public class GridMap : MonoBehaviour
{
    public MapData_SO mapData;
    public GridType gridType;
    private Tilemap currentTilemap;

    private void OnEnable()
    {
        if (!Application.IsPlaying(this))
        {
            currentTilemap = GetComponent<Tilemap>();

            if (mapData != null)
            {
                mapData.tileProperties.Clear();
            }
        }
    }

    private void OnDisable()
    {
        if (!Application.IsPlaying(this))
        {
            currentTilemap = GetComponent<Tilemap>();

            if (mapData != null)
            {
                UpdateTileProperties();

#if UNITY_EDITOR
                EditorUtility.SetDirty(mapData);
                AssetDatabase.SaveAssets();
#endif
            }

        }
    }

    private void UpdateTileProperties()
    {
        // 压缩地图,确保每一块都存在一个Tile 
        currentTilemap.CompressBounds();

        Vector3Int startPos = currentTilemap.cellBounds.min;
        Vector3Int endPos = currentTilemap.cellBounds.max;

        for (int x = startPos.x; x < endPos.x; x++)
        {
            for (int y = startPos.y; y < endPos.y; y++)
            {
                TileBase tile = currentTilemap.GetTile(new Vector3Int(x, y, 0));

                if (tile != null)
                {
                    TileProperty property = new TileProperty()
                    {
                        gridType = this.gridType,
                        tileCoordinate = new Vector2Int(x, y),
                        boolTypeValue = true
                    };

                    mapData.TryAdd(property);
                }
            }
        }
    }



}

